﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.IO;
using StockTrader.BusinessService.DataContract.Mortgate;
using Mortgage.DAL;
using MortgageMonitor.BSL;

namespace StockTrader.FrontEnd.MarketViewer.DAL
{
    public partial class DataConvertion : Form
    {
        private AsyncDataProcessor processor;

        public DataConvertion()
        {
            InitializeComponent();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                btnImport.Enabled = false;
                ImportRptData(dtSelected.Value, txtFileName.Text, chkSingleMode.Checked);
            }
            catch
            {
                MessageBox.Show("Lỗi khi xử lý file dữ liệu.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Market file (*.xls)|*.xls"; dialog.InitialDirectory = "\\\\dc\\data\\HoSE Info\\";
            dialog.Title = "Select data file to import ...";
            if (dialog.ShowDialog() == DialogResult.OK)
                txtFileName.Text = dialog.FileName;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void ImportRptData(DateTime transDate, string sourceFile, bool SingleMode)
        {
            int importedRecord = 0;
            try
            {
                ResetIndicators();
                ApplicationClass app = new ApplicationClass();
                Workbook book = null;
                Worksheet sheet = null;
                Range range = null;
                int[] Columns = { 1, 2 };

                try
                {
                    app.Visible = false;
                    app.ScreenUpdating = false;
                    app.DisplayAlerts = false;

                    book = app.Workbooks.Open(sourceFile, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                         , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                        , Type.Missing, Type.Missing, Type.Missing);
                    sheet = (Worksheet)book.Worksheets[1];

                    // get a range to work with
                    range = sheet.get_Range("A1", Type.Missing);
                    // get the end of values to the right (will stop at the first empty cell)
                    range = range.get_End(XlDirection.xlToRight);
                    // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                    range = range.get_End(XlDirection.xlDown);

                    // get the address of the bottom, right cell
                    string downAddress = range.get_Address(
                        false, false, XlReferenceStyle.xlA1,
                        Type.Missing, Type.Missing);

                    // Get the range, then values from a1
                    range = sheet.get_Range("A1", downAddress);
                    object[,] values = (object[,])range.Value2;
                    MortgageMornitorDAL dac = new MortgageMornitorDAL();
                    if (SingleMode)
                        dac.DeleteLoanRate(transDate);
                    int totalRecord = values.GetLength(0);
                    prgImport.Maximum = totalRecord;
                    UpdateLabels("Đang cập nhật dữ liệu, xin vui lòng chờ ...", totalRecord);
                    DateTime starttime = DateTime.Now;

                    for (int i = 1; i <= totalRecord; i++)
                    {
                        importedRecord++;
                        processor = new AsyncDataProcessor(new LoanRateData(
                            transDate, values[i, 1].ToString().Trim(),
                            Convert.ToDecimal(values[i, 2].ToString())),
                            prgImport, lblSucess, importedRecord, starttime, totalRecord, lblElapsed,
                            lblRemain, lblSpeed, lblPercent, lblStatus);
                        processor.Execute();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "OopsQ!");
                }
                finally
                {
                    range = null;
                    sheet = null;
                    if (book != null)
                        book.Close(false, Type.Missing, Type.Missing);
                    book = null;
                    if (app != null)
                        app.Quit();
                    app = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Import result", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void ResetIndicators()
        {
            lblElapsed.Text = "-- : -- : --";
            lblRemain.Text = "-- : -- : --";
            lblTotal.Text = "0";
            lblSucess.Text = "0";
            lblStatus.Text = string.Empty;
            lblSpeed.Text = "0";
            lblPercent.Text = "0";

            prgImport.Value = 0;
        }

        private void UpdateLabels(string status, int total)
        {
            lblStatus.Text = status;
            lblTotal.Text = total.ToString("N0");
        }

        private void txtFileName_TextChanged(object sender, EventArgs e)
        {
            ResetIndicators();
            btnImport.Enabled = true;
        }

        private void dtSelected_ValueChanged(object sender, EventArgs e)
        {
            ResetIndicators();
            btnImport.Enabled = true;
        }

    }
}
